import { computed, onUnmounted } from "vue";

export default function() {
    let ws: WebSocket, _uid: string;

    const connectWS = (uid: string) => {
        _uid = uid;
        ws = new WebSocket(`wss://yunfeng.icu/webSocket/${uid}`);
        ws.onopen = () => {
            console.log('WebSocket打开连接');
        }
    
        ws.onmessage = function (event) {
            console.log('WebSocket收到消息：%c' + event.data, 'color:green');
            //获取服务端消息
        };
    
        /**
         * 关闭连接
         */
        ws.onclose = function (event) {
            console.log('WebSocket关闭连接');
        };
    
        /**
         * 通信失败
         */
        ws.onerror = function (event) {
            console.log('WebSocket发生异常');
        };
        return ws;
    }

    // const getStatus = computed(() => ws.readyState)

    const closeWs = () => {
        console.log(`WebSocket当前状态：${ws.readyState}`);
        if (ws.readyState === ws.OPEN) {
            ws.close();
        }
    }

    const sendMsg = (msg: string) => {
        ws.send(msg);
    }

    onUnmounted(() => {
        closeWs();
    })

    return {
        connectWS,
        // getStatus,
        closeWs,
        sendMsg
    }
}